package com.example.downloaddemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * Created by xiewei on 15-2-3.
 */
public class DownThread extends Thread{
	private int threadId;
	private int startPos;
	private int endPos;
	private int compeleteSize;
	private String urlstr;
	private String path;
	private Dao dao;
	private DownLoader downLoader;
	private Handler handler;

	public DownThread(DownLoader downLoader, BlockInfo info, String path, Dao dao, Handler handler) {
		this.downLoader=downLoader;
		this.threadId=info.getThreadId();
		this.startPos=info.getStartPos();
		this.endPos=info.getEndPos();
		this.compeleteSize=info.getCompeleteSize();
		this.urlstr=info.getUrl();
		this.path=path;
		this.dao=dao;
		this.handler=handler;
	}

	@Override
	public void run() {
		RandomAccessFile file = null;
		InputStream in = null;
		HttpURLConnection conn=null;
		try {
			Log.i("msg","thread");
			URL url = new URL(urlstr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestProperty("Range", "bytes=" + (startPos + compeleteSize) + "-" + endPos);
			file = new RandomAccessFile(path, "rwd");
			file.seek(startPos + compeleteSize);
			in = conn.getInputStream();
			byte[] data = new byte[2048];
			int len = 0;
			int tlen=0;
			while ((len = in.read(data)) != -1) {
				file.write(data, 0, len);
				compeleteSize+=len;
				tlen+=len;
				if(tlen>=50*2048){


					dao.updataInfo(threadId, compeleteSize, urlstr);
					Message msg = handler.obtainMessage();
					msg.what = 1;
					msg.obj = urlstr;
					msg.arg1 = tlen;
					msg.sendToTarget();
					tlen=0;
				}

				if (downLoader.state == Constants.PAUSE) {
					return;
				}

			}
			if(len==-1){
				dao.updataInfo(threadId, compeleteSize, urlstr);
				Message msg = handler.obtainMessage();
				msg.what = 1;
				msg.obj = urlstr;
				msg.arg1 = tlen;
				msg.sendToTarget();
			}


		} catch (IOException e) {
			Log.i("msg",e.toString());
			e.printStackTrace();
		} finally {
			try {
				in.close();
				file.close();
				conn.disconnect();
				//dao.closeDb();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
